package com.github.bobjoy.java.rpc.provider;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class ExporterTask implements Runnable {

    private Socket client;

    public ExporterTask(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {

        ObjectInputStream input = null;
        ObjectOutputStream output = null;

        try {

            input = new ObjectInputStream(client.getInputStream());

            String interfaceName = input.readUTF();
            Class<?> service = Class.forName(interfaceName);

            String methodName = input.readUTF();
            Class<?>[] paramTypes = (Class<?>[]) input.readObject();
            Object[] args = (Object[]) input.readObject();

            Method method = service.getMethod(methodName, paramTypes);
            Object result = method.invoke(service.newInstance(), args);

            output = new ObjectOutputStream(client.getOutputStream());
            output.writeObject(result);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
